﻿//------------------------------------------------------------------------------
//  Namespace: FruitVentDesign.Commands
//  
//  Function： N/A
//  Name： SimpleCommand
//  
//  Ver       Time                     Author
//  0.10      2021/6/27 22:12:13      FruitVent
//
//  此代码版权归作者本人FruitVent所有
//  源代码使用协议遵循本仓库的开源协议及附加协议，若本仓库没有设置，则按MIT开源协议授权
//  CSDN博客：https://blog.csdn.net/weixin_39552347
//  源代码仓库：https://gitee.com/fruitvent
//  感谢您的下载和使用
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
using System;
using System.Windows.Input;

namespace FruitVentDesign.Commands
{
    internal class SimpleCommand : ICommand
	{
		private readonly Action _onExecute;
		private readonly Func<bool> _canExecute;
		public SimpleCommand(Action onExecute, Func<bool> canExecute = null)
		{
			_onExecute = onExecute;
			_canExecute = canExecute;
		}

		public event EventHandler CanExecuteChanged
		{
			add
			{
				CommandManager.RequerySuggested += value;
			}
			remove
			{
				CommandManager.RequerySuggested -= value;
			}
		}

		public bool CanExecute(object parameter)
		{
			if (_canExecute == null) { return true; }
			else { return _canExecute(); }
		}

		public void Execute(object parameter)
		{
			_onExecute?.Invoke();
		}
	}

    public class SimpleCommand<T> : ICommand
    {
        private readonly Action<T> _onExecute;
        private readonly Func<T, bool> _canExecute;
        public SimpleCommand(Action<T> onExecute, Func<T, bool> canExecute = null)
        {
            _onExecute = onExecute;
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        /// <summary>
        /// 是否可执行
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            T t = (T)parameter;
            if (_canExecute == null) { return true; }
            else { return _canExecute(t); }
        }

        // <summary>
        /// 执行
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            T t = (T)parameter;
            if (_canExecute != null && !_canExecute(t)) { return; }
            _onExecute?.Invoke(t);
        }
    }
}
